package com.atguigu.yygh.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.mq.pojo.MqConst;
import com.atguigu.yygh.mq.service.RabbitService;
import com.atguigu.yygh.order.mapper.PaymentMapper;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.utils.HttpRequestHelper;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 创建支付记录
 * 先查询，看数据库中是否存在支付记录
 * @author: 化一帆
 * @date: 2022/12/9 20:48
 * @version: v1.0
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, PaymentInfo> implements PaymentService {

    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private OrderService orderService;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public void createPayment(OrderInfo orderInfo, Integer status) {

        //根据订单id和支付类型，查询支付记录表中是否存在相同的订单
        QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderInfo.getId());//订单id
        wrapper.eq("payment_type", status);//支付类型
        Integer count = baseMapper.selectCount(wrapper);
        if(count>0){
            return;
        }

        //添加支付记录
        PaymentInfo paymentInfo = new PaymentInfo();

        paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
        paymentInfo.setOrderId(orderInfo.getId());//订单id
        paymentInfo.setPaymentType(status);//支付类型


//        paymentInfo.setTradeNo();支付完成后的微信端返回的流水号
//        paymentInfo.setCallbackTime(); 支付完成的时间
//        paymentInfo.setCallbackContent(); 支付完成后，微信端返回的所有数据
        paymentInfo.setTotalAmount(orderInfo.getAmount());

        Date reserveDate = orderInfo.getReserveDate();
        String date = new DateTime(reserveDate).toString("yyyy-MM-dd");
        String patientName = orderInfo.getPatientName();
        String hosname = orderInfo.getHosname();
        String depname = orderInfo.getDepname();
        String title = orderInfo.getTitle();

        paymentInfo.setSubject(date+patientName+hosname+depname+title);//支付交易内容   yyyy-MM-dd|张三|协和医院|心内科|教授
        paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());//支付中（未支付）

        baseMapper.insert(paymentInfo);



        //给用户发送短信通知
        MsmVo msmVo = new MsmVo();

        Long userId = orderInfo.getUserId();
        msmVo.setPhone(patientFeignClient.getUserPhone(userId));
        msmVo.getParam().put("message","【尚医通】你好，支付成功！");
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM,MqConst.ROUTING_MSM_ITEM,msmVo);

    }

    /**
     * @description: 二维码支付成功后，修改数据库中对应的数据
     * @author 化一帆
     * @date 2022/12/11 18:15
     */
    @Override
    public void afterSuccess(Long orderId, Map<String, String> map) {

        OrderInfo orderInfo = orderService.getById(orderId);

        //1、调用医院端的接口，修改支付状态，改成1（5.2.更新支付状态）

        String url = "http://localhost:9998/order/updatePayStatus";

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("hosRecordId",orderInfo.getHosRecordId());//医院端订单的主键

        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, url);

        if(jsonObject.getInteger("code")!=200){
            throw new YyghException(20001,"医院端接口调用失败");
        }

        //2、修改平台端的订单状态，改成1
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());//1
        orderService.updateById(orderInfo);


        //3、修改平台端该订单的支付记录（payment_status trade_no callback_time callback_content）
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("out_trade_no",orderInfo.getOutTradeNo());
//        queryWrapper.eq("order_id",orderInfo.getId());

        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);

        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus());
        paymentInfo.setTradeNo(map.get("transaction_id"));//支付成功后，微信端返回的transaction_id
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(map.toString());

        baseMapper.updateById(paymentInfo);
    }

    /**
     * @description:  根据orderid查询支付记录
     * @author 化一帆
     * @date 2022/12/11 19:47
     */
    @Override
    public PaymentInfo getPaymentByOrderId(Long orderId) {
        QueryWrapper<PaymentInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);

        PaymentInfo paymentInfo = baseMapper.selectOne(queryWrapper);
        return paymentInfo;
    }
}

